import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.*;

public class httphandler {

	private Socket socket;
	private httpresponse response;

	public httphandler(Socket socket) {
		this.socket = socket;
	}

	public void execGET(String filePath, String multiHoming) throws IOException {
		
		response = new httpresponse(socket.getOutputStream());
		
		String multiHome = "";
		File file;
		
		if(properties.MultiHomeDirs.containsKey(multiHoming.replace(":" + properties.Port, "")))
		{
			multiHome = (String) properties.MultiHomeDirs.get(multiHoming.replace(":" + properties.Port, ""));
			filePath = multiHome + filePath;
		}
		/*
		//Property-Datei ->FQDNs
		if(!multiHoming.equals("") && multiHoming.equals("127.0.0.1:33005"))
		{
			multiHome = "ordner1";
			filePath = multiHome + filePath;
		}*/
		/*else if(!multiHoming.equals("") && multiHoming.equals("bla.de"))
		{
			filePath = "ordner1" + filePath;
		}
		else if(!multiHoming.equals("") && multiHoming.equals("gedoehns.de"))
		{
			filePath = "ordner2" + filePath;
		}*/
		
		if(filePath.equals(multiHome + "/"))
		{
			file = new File(multiHome + "/index.html");
		}
		else 
		{
			if(new File(filePath).exists ())
			{
				file = new File(filePath);
			}
			else
			{
				file = new File(multiHome + "/error.html");
			}
		}
		
		FileInputStream fis = null;
		try {
			
			fis = new FileInputStream(file);
			String type = URLConnection.getFileNameMap().getContentTypeFor(
					file.getPath());
			if (type == null) {
				type = "application/octet-stream";
			}
			response.addHeader("Content-Type", type);
			response.addHeader("Content-Length", String.valueOf(file.length()));
			response.printStatus(200);
			response.printHeaders();
			OutputStream out = response.getOutputStream();
			byte data[] = new byte[1024];
			int cnt;
			while ((cnt = fis.read(data)) != -1) {
				out.write(data, 0, cnt);
			}
			out.flush();
		} catch (SecurityException e) {

		} catch (FileNotFoundException e) {
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (IOException e) {
			}
		}
		
	}

	public void execHEAD() {

	}

	public void execPOST() {

	}

	public void execMULTI() {

	}

}
